package cn.stylefeng.guns.modular.business.util;

import cn.hutool.core.util.ObjectUtil;
import cn.stylefeng.guns.core.enums.CoreExceptionEnum;
import cn.stylefeng.guns.core.exception.CustomException;
import cn.stylefeng.guns.modular.business.app.controller.req.LoginReqVo;
import cn.stylefeng.guns.sys.modular.user.entity.SysUser;
import cn.stylefeng.guns.sys.modular.user.service.SysUserService;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @Author liwenlong
 */

@Component
public class JudgeLogicUtil {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private BusinessUtil businessUtil;

    /**
     * 数据判断
     */
    public static Set<Map.Entry<String, Object>> judgeObjectField(Object object) {

        //需要修改的数据 KEY 字段名  value 属性值
        Map<String, Object> updateMap = new HashMap<>();

        //根据对象反射
        Class<?> clazz = object.getClass();

        //根据反射机制获取对象的所有字段，包含public、private和proteced
        Field[] declaredFields = clazz.getDeclaredFields();

        //循环判断对象中的字段
        Arrays.stream(declaredFields).forEach(field -> {
            //设置属性可访问
            field.setAccessible(true);
            try {
                //得到属性值
                Object value = field.get(object);
                TableField annotation = field.getAnnotation(TableField.class);

                if (ObjectUtil.isNotEmpty(value) && annotation != null && annotation.exist()) {
                    updateMap.put(annotation.value(), value);
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        });

        Set<Map.Entry<String, Object>> entries = updateMap.entrySet();

        return entries;
    }

    /**
     * 验证登入账号
     *
     * @return
     */
    public Long checkLoginUser(LoginReqVo loginReqVo) {

        Long userId = null;

        SysUser sysUser = sysUserService.getBaseMapper().selectOne(new QueryWrapper<SysUser>().lambda()
                .eq(SysUser::getAccount, loginReqVo.getAccount())
                .eq(SysUser::getTenantId, loginReqVo.getTenantId())
        );

        if (sysUser == null) {
            throw new CustomException(CoreExceptionEnum.ACCOUNT_NOT_EXIST);
        }

        userId = sysUser.getId();

        //sysUser.setClientId(loginReqVo.getClientId());
        //sysUserService.update().set("client_id", loginReqVo.getClientId()).eq("id", userId).update();

        return userId;
    }


}
